package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	auth2 "github.com/silenceper/wechat/v2/miniprogram/auth"
	"time"
	"yxService/app/models"
	"yxService/app/pkg/app"
	"yxService/app/pkg/errcode"
	"yxService/app/pkg/logger"
	"yxService/app/pkg/rdb"
	"yxService/app/pkg/util"
	"yxService/app/pkg/wechat"
)

type Wechat struct {
}

/*
微信授权auth 获取sessionKey
*/
func (w Wechat) Auth(c *gin.Context) {
	var resMap map[string]string = make(map[string]string)
	r := app.NewResponse(c)
	mina := wechat.Mina
	auth := mina.GetAuth()
	var session auth2.ResCode2Session
	var err error
	session, err = auth.Code2Session(c.Query("code"))
	//判断是否出现错误
	if err != nil {
		logger.Log.Infof("code2Session error:%s", err)
		resMap["error"] = err.Error()
		r.ToErrorResponse(err, errcode.WechatError)
		return
	}
	fmt.Printf("sessionKey is: %s", session.SessionKey)
	// 生成随机数
	randomStr := fmt.Sprintf("%d%s", time.Now().Unix(), util.RandString(10))

	//存储sessionKey进入redis
	rdb.RedisClient.Set(rdb.Ctx, randomStr, session.SessionKey, 30*time.Minute)
	rdb.RedisClient.Set(rdb.Ctx, "openId"+randomStr, session.OpenID, 30*time.Minute)
	resMap["session_id"] = randomStr
	r.ToResponse(resMap, errcode.Success)
}

//登录
func (w Wechat) Login(c *gin.Context) {
	//mina := wechat.Mina
	r := app.NewResponse(c)
	var req models.WechatLoginReq
	//encryptedData := c.PostForm("encryptedData")
	//iv := c.PostForm("iv")
	//sessionId := c.PostForm("session_id")
	_ = c.ShouldBindJSON(&req)
	//根据session_id获取对应sessionKey
	//val, err := rdb.RedisClient.Get(rdb.Ctx, req.SessionId).Result()
	openId, err := rdb.RedisClient.Get(rdb.Ctx, "openId"+req.SessionId).Result()
	if err != nil {
		if err.Error() == "redis: nil" {
			r.ToErrorResponse(err, errcode.SessionIdError)
			return
		}
		logger.Log.Infof("get sessionId exception ,error is :", err.Error())
		r.ToErrorResponse(err, errcode.RedisError)
		return
	}
	//解密获取用户数据
	//data, err := mina.GetEncryptor().Decrypt(val, req.EncryptedData, req.Iv)
	//if err != nil {
	//	logger.Log.Infof("get sessionId exception ,error is :", err.Error())
	//	r.ToErrorResponseWithErr(err, errcode.WechatError)
	//	return
	//}

	//新增用户数据
	user := models.User{
		Nickname: req.UserInfo.NickName,
		Username: "",
		Gender:   req.UserInfo.Gender,
		OpenId:   openId,
		Province: req.UserInfo.Province,
		County:   req.UserInfo.Country,
		City:     req.UserInfo.City,
		Address:  "",
		//Status:   true,
		//Type:     1,
		Avatar: req.UserInfo.AvatarUrl,
		//Phone:    data.PhoneNumber,
	}
	//查询用户是否存在 存在就更新数据
	err = user.UpdateOrCreateUser()

	if err != nil {
		r.ToErrorResponse(err, errcode.RedisError)
		return
	}
	var resMap = make(map[string]interface{})
	//生成token
	token, err := app.GenerateToken(&user)

	if err != nil {
		r.ToErrorResponse(err, errcode.DBException)
	}
	resMap["token"] = token
	resMap["user"] = user
	r.ToResponse(resMap, errcode.Success)
}
